package lovebomb.jfilesearch.engine.filetype;

import java.io.File;
import java.io.FileInputStream;

import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDEmbeddedFilesNameTreeNode;
import org.apache.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification;
import org.apache.pdfbox.util.PDFTextStripper;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

public class PDFRead {

	private static PDFRead pdfRead = null;
	
	private PDFRead(){
		
	}
	
	public static PDFRead getInstance(){
		if( pdfRead == null){
			pdfRead = new PDFRead();
		}
		return pdfRead;
	}
	
	@SuppressWarnings("finally")
	public String readPDF( String strFile){
		StringBuffer strNote = new StringBuffer();
		PdfReader reader = null;
		
        PDFParser parser = null;
        PDFTextStripper pdfStripper = null;
        PDDocument pdDoc = null;
        COSDocument cosDoc = null;
		try {
			reader = new PdfReader(strFile);
            int n = reader.getNumberOfPages();
            for (int i = 1; i <= n; i++) {
                strNote.append(PdfTextExtractor.getTextFromPage(reader, i));              
            }
            
            if( strNote==null || strNote.toString().trim().equals("")){
            	
	            
	            parser = new PDFParser(new FileInputStream( new File( strFile)));
	            parser.parse();
	            cosDoc = parser.getDocument();
	            pdfStripper = new PDFTextStripper();
	            pdDoc = new PDDocument(cosDoc);
	
	            int page=0;
	            
	            while (page < pdDoc.getNumberOfPages()) {
	                page++;
	                pdfStripper.setStartPage(page);
	                pdfStripper.setEndPage(page + 1);
	                strNote.append(pdfStripper.getText(pdDoc));
	            }
            }
            
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			return strNote.toString();
		}	
		
		
	}
}
